package dao

import (
	"context"
	"cron_table_admin/global"
	"cron_table_admin/internal/model"
	"errors"

	"gorm.io/gorm"
)

type CronDao struct{}

func NewCronDao() *CronDao {
	return &CronDao{}
}

func (d *CronDao) Create(ctx context.Context, cron *model.Cron) (err error) {
	cronCurd := &DbCrud[model.Cron]{
		Db:       global.GORM_DB,
		DataList: []*model.Cron{cron},
	}
	_, err = cronCurd.DBCreate(ctx)
	if err != nil {
		return err
	}
	return nil
}

func (d *CronDao) Update(ctx context.Context, updateData map[string]any, conditions []map[string]any) (int64, error) {
	cronCurd := &DbCrud[model.Cron]{
		Db:         global.GORM_DB,
		DataMap:    updateData,
		Conditions: conditions,
	}
	affectRows, err := cronCurd.DBUpdate(ctx)
	if err != nil {
		return 0, err
	}
	return affectRows, nil
}

func (d *CronDao) Query(ctx context.Context, conditions []map[string]any, pageNo, pageSize int32) ([]*model.Cron, error) {
	cronCurd := &DbCrud[model.Cron]{
		Db:         global.GORM_DB,
		Conditions: conditions,
		PageSize:   pageSize,
		PageNo:     pageNo,
	}
	dataList, err := cronCurd.DBRead(ctx)
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, err
	}
	return dataList, nil
}

func (d *CronDao) Count(ctx context.Context, conditions []map[string]any) (int64, error) {
	cronCurd := &DbCrud[model.Cron]{
		Db:         global.GORM_DB,
		Conditions: conditions,
	}
	num, err := cronCurd.DBCount(ctx)
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		return 0, err
	}
	return num, nil
}

func (d *CronDao) GetDetailById(ctx context.Context, id int64) (*model.Cron, error) {
	cronCurd := &DbCrud[model.Cron]{
		Db: global.GORM_DB,
		Conditions: []map[string]any{
			{"id": id},
		},
	}
	dataList, err := cronCurd.DBRead(ctx)

	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, nil
		}
		return nil, err
	}
	return dataList[0], nil
}
